import React, { Component } from 'react'
import styles from './index.module.scss'
// 加载本地图片
import loginBgImg from '../../assets/img/login_bg.png'
import loginIcon from '../../assets/img/login_icon.png'
import { Form, Input, Button, Checkbox, Row, Col, message } from 'antd'
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons'
import { login } from '@/api/user'
import { saveToken } from '@/utils/token'
// 导入子组件
import Register from './Register'

export default class Login extends Component {
  constructor () {
    super()

    document.title = '黑马面面'

    this.state = {
      loginCaptchaUrl: process.env.REACT_APP_BASEURL + '/captcha?type=login'
    }
  }

  // 点击获取验证码的图片
  changeLoginCaptchaUrl = () => {
    this.setState({
      loginCaptchaUrl:
        process.env.REACT_APP_BASEURL +
        `/captcha?type=login&t=${new Date() - 0}`
    })
  }

  // 登录完成了按钮
  onFinish = async values => {
    // console.log(values)
    const res = await login(values)

    if (res.code !== 200) {
      message.error(res.message)

      this.changeLoginCaptchaUrl()
    } else {
      //1、提示
      message.success('登录成功~')
      //2、保存token 到本地
      saveToken(res.data.token)
      //3、跳转到layout页面
      this.props.history.push('/layout')
    }
  }

  // ref属性
  registerRef = React.createRef()

  // 注册
  register = () => {
    // React中更改模型值，要使用setState
    this.registerRef.current.setState({
      isModalVisible: true
    })
  }

  render () {
    return (
      <div className={styles['login-container']}>
        {/* 左边 */}
        <div className={styles.left}>
          <div className={styles['title-box']}>
            <img src={loginIcon} alt='' />
            <span className={styles.title}>黑马面面</span>
            <span className={styles.line}></span>
            <span className={styles['sub-title']}>用户登录</span>
          </div>
          <Form
            name='normal_login'
            style={{ marginTop: 20 }}
            initialValues={{
              phone: '18511111111',
              password: '12345678',
              agreement: true
            }}
            size='large'
            onFinish={this.onFinish}
          >
            <Form.Item
              name='phone'
              rules={[
                {
                  validator: (_, value) => {
                    if (!value) return Promise.reject('手机号不能为空')

                    const reg = /^1[3456789][0-9]{9}$/
                    if (!reg.test(value)) return Promise.reject('手机号不合法')

                    return Promise.resolve()
                  }
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input
                prefix={<UserOutlined className='site-form-item-icon' />}
                placeholder='请输入手机号'
              />
            </Form.Item>
            <Form.Item
              name='password'
              rules={[
                {
                  required: true,
                  message: '密码不能为空'
                },
                {
                  min: 6,
                  max: 16,
                  message: '密码长度需要在6-16位之间'
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input
                prefix={<LockOutlined className='site-form-item-icon' />}
                type='password'
                placeholder='请输入密码'
              />
            </Form.Item>
            <Row>
              <Col span={16}>
                <Form.Item
                  name='code'
                  rules={[
                    {
                      required: true,
                      message: '验证码不能为空'
                    }
                  ]}
                  validateTrigger='onBlur'
                >
                  <Input
                    prefix={<KeyOutlined className='site-form-item-icon' />}
                    placeholder='请输入验证码'
                  />
                </Form.Item>
              </Col>
              <Col style={{ marginLeft: 15 }} span={7}>
                <img
                  src={this.state.loginCaptchaUrl}
                  style={{ width: '100%', height: 40 }}
                  alt=''
                  onClick={this.changeLoginCaptchaUrl}
                />
              </Col>
            </Row>
            <Form.Item
              name='agreement'
              valuePropName='checked'
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject('必须勾选用户协议')
                }
              ]}
            >
              <Checkbox>
                我已阅读并同意 <a href='http://www.baidu.com'>用户协议</a>和
                <a href='http://www.jd.com'>隐私条款</a>
              </Checkbox>
            </Form.Item>

            <Form.Item>
              {/* htmlType这个必须有，才能执行onFinish方法 */}
              <Button
                type='primary'
                htmlType='submit'
                className='login-form-button'
                block
              >
                登 录
              </Button>
              {/* block代表独占一行 */}
              <Button
                style={{ marginTop: 20 }}
                type='primary'
                className='login-form-button'
                block
                onClick={this.register}
              >
                注 册
              </Button>
            </Form.Item>
          </Form>
        </div>
        {/* 右边 */}
        <div>
          {/* JSX不行，它会报错，报加载不到的错误 */}
          {/* <img src='@/assets/img/login_bg.png' /> */}
          <img src={loginBgImg} alt='' />
        </div>
        {/* 注册子组件 */}
        <Register ref={this.registerRef} />
      </div>
    )
  }
}
